package com.example.gobangssm.api;

import com.example.gobangssm.model.User;
import com.example.gobangssm.model.UserMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserAPI {
    @Resource
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest request){
        //关键操作，根据username去数据库进行查询
        //如果能找到匹配用户，密码也一致，则登陆成功
        User user = userMapper.selectByName(username);
        System.out.println("[login] username="+username);
        if(user==null || !user.getPassword().equals(password)){
            //登陆失败
            System.out.println("登陆失败！");
            return new User();
        }
        HttpSession httpSession=request.getSession(true);
        httpSession.setAttribute("user",user);
        return user;
    }
    @PostMapping("/register")
    public Object register(String username,String password){
        try{
            User user=new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            return user;
        }catch (org.springframework.dao.DuplicateKeyException e){
            User user=new User();
            return user;
        }
    }

    @GetMapping("/userinfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest request){
        try{
            HttpSession httpSession=request.getSession(false);
            User user=(User)httpSession.getAttribute("user");
            return user;
        }catch (NullPointerException e){
            return new User();
        }
    }
}
